﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using DocumentBuilder.Components;
using DocumentBuilder.Controls.DataSources;

namespace DocumentBuilder.Controls
{
    public enum TemplateContainer
    {
        Div,
        Li,
        Td
    }

    public class Repeater : IBindableControl
    {
        private List<Components.ViewObject> _dataSource = null;

        public String ClassName { get; set; }
        public ItemTemplate ItemTemplate { get; private set; }
        
        private IDictionary<String, IDataSource> DataSources { get; set; }

        private Repeater()
        {
            DataSources = new Dictionary<string, IDataSource>();
        }

        public static Repeater Create(Document context, XmlNode repeaterNode)
        {
            var repeater = new Repeater();

            /* Create ItemTemplate
             */
            var templateNode = repeaterNode.SelectSingleNode("./itemtemplate");
            if (templateNode == null)
                throw new Exception("Repeater control cannot be created without ItemTemplate");

            repeater.ItemTemplate = ItemTemplate.Create(context, templateNode);

            /* Create Datasoures
             */
            var dataNodes = repeaterNode.SelectNodes("./datasources/data");
            if (dataNodes != null)
            {
                foreach (XmlNode dataNode in dataNodes)
                {
                    var dataSource = DataSourceFactory.Create(context, dataNode);
                    repeater.DataSources.Add(dataSource.Id, dataSource);
                }
            }

            return repeater;
        }

        #region IBindableControl Members

        public void Bind(System.Data.DataSet dataSet)
        {
            throw new NotImplementedException();
        }

        public void Bind(List<Components.ViewObject> objects)
        {
            _dataSource = objects;
        }

        public object GetDatasource()
        {
            throw new NotImplementedException();
        }

        #endregion

        #region IControl Members

        public void PaintHtmlString(StringBuilder htmlCanvas)
        {
            var dataSource = DataSources[ItemTemplate.BindsWith];

            if (dataSource is IIterableDataSource<IDataItem>)
            {
                foreach (var dataItem in (IIterableDataSource<IDataItem>)dataSource)
                {
                    htmlCanvas.AppendLine(ItemTemplate.CreateWith(dataItem));
                }
            }
            else
            {
                htmlCanvas.AppendLine(ItemTemplate.CreateWith(dataSource));
            }
        }

        #endregion
    }
}
